/**
 * 
 * 登陆模块
 * 
 * 登陆，并返回用户信息和授权token
 * 
 */

var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var jwt = utils.jwt;
var User = require('./dal/user.js')

/**
 * 登陆
 */
const loginFn = async (req, res, next) => {

    var body = req.body || req.query;

    // --------帐号密码有值判断
    if (!body.userid && !body.userpw) {
        return res.send({ code: 0, msg: "请输入账号和密码" });
    }

    //  -------- 获取用户信息
    var whereData = {
        id: body.userid,
        userpw: body.userpw
    }

    try {
        // -------- 搜索用户
        var user = new User(whereData);
        var results = await user.fullSelect();
        if (results.length > 0) {
            // --------- 授权
            var token = await jwt.encode(body.userid);
            return res.send({ code: 1, token: token, userinfo: results[0] });
        } else {
            return res.send({ code: 0, msg: '密码错误' });
        }
    } catch (error) {
        res.send({ code: 0, msg: error })
    }

}

server.post({ path: routerApi, name: routerApi }, loginFn);
